package com.frxuexi.demo.news

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.frxuexi.base.entity.RecordEntity
import com.frxuexi.demo.R
import com.frxuexi.demo.databinding.ItemNewsBinding

class NewsPageAdapter:PagingDataAdapter<RecordEntity,NewsPageAdapter.MyViewHolder>(diffUtilCallBack) {
    companion object{
        private val diffUtilCallBack = object :ItemCallback<RecordEntity>(){
            override fun areItemsTheSame(oldItem: RecordEntity, newItem: RecordEntity): Boolean {
                return oldItem.id==newItem.id
            }

            override fun areContentsTheSame(oldItem: RecordEntity, newItem: RecordEntity): Boolean {
                return oldItem==newItem
            }
        }
    }
    lateinit var monItemClickListener: OnItemClickListener
    lateinit var monItemLongClickListener: OnItemLongClickListener
    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val item = getItem(position)
        holder.binding?.apply {
            txtName.text=item?.title
            txtContent.text=item?.content
            tvLookNumber.text="阅读量：${item?.looks}"
            tvTime.text=item?.createTime
            Glide.with(holder.itemView).load(item?.imgurl).circleCrop().into(imgUrl)
        }
        holder.itemView.apply {
            setOnClickListener {
                monItemClickListener.OnItemClick(position = position,item!!)
            }
            setOnLongClickListener {
                monItemLongClickListener.onItemLongClick(item!!)

            }
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_news, parent, false)
        return MyViewHolder(view)
    }

    class MyViewHolder(itemView:View): RecyclerView.ViewHolder(itemView){
        val binding:ItemNewsBinding?=DataBindingUtil.bind<ItemNewsBinding>(itemView)
    }

    fun setOnItemClickListener(listener: OnItemClickListener?) {
        this.monItemClickListener = listener!!
    }

    fun setOnItemLongClickListener(listener: OnItemLongClickListener?) {
        this.monItemLongClickListener = listener!!
    }


}

interface OnItemClickListener{
    fun OnItemClick(position: Int,recordEntity: RecordEntity)
}


interface OnItemLongClickListener {
    fun onItemLongClick(recordEntity: RecordEntity): Boolean
}
